package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;


@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO loginDTO) {



        String openid = getOpenid(loginDTO.getCode());
        //判断openid是否为空,抛出业务异常
        if (openid == null || openid.isEmpty()) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //TODO完善代码
        //判断该用户是否是新用户,所以获取的openid需要存入数据库中,如果是新用户,则自行封装一个user对象,封装到数据库中,
        User registerUser = userMapper.getUserByOpenid(openid);
        if (registerUser == null) {//说明是新用户
            registerUser = new User();
            registerUser.setOpenid(openid);
            registerUser.setCreateTime(LocalDateTime.now());

            userMapper.insert(registerUser);
        }

        //如果不是,就从数据库中获取用户信息
        //微信登陆

        //生成jwt令牌
        String authentication = jwtInit(registerUser.getId());
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(registerUser, userLoginVO);
        userLoginVO.setOpenid(openid);
        userLoginVO.setToken(authentication);
        userLoginVO.setId(BaseContext.getCurrentId());

        return userLoginVO;
    }

    private String jwtInit(Long id){
        //生成JWT令牌
        HashMap<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,id);

        return JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
    }


    private String getOpenid(String code) {
        //调用微信接口服务,获得当前微信用户的openid
        HashMap<String,String> login_param = new HashMap<>();
        login_param.put("appid", weChatProperties.getAppid());
        login_param.put("secret", weChatProperties.getSecret());
        login_param.put("js_code", code);
        login_param.put("grant_type", "authorization_code");//授权类型,指定值为 authorization_code
        String jsonText = HttpClientUtil.doGet(WX_LOGIN_URL, login_param);

        JSONObject jsonObject = JSON.parseObject(jsonText);
        return jsonObject.getString("openid");
    }
}
